import React, { useEffect, useState, useCallback } from 'react';
import { ScrollView, View, Text, TouchableOpacity, Alert, ActivityIndicator, StyleSheet } from 'react-native';
import DeviceCard from '@/components/features/device/DeviceCard';
import { CurrentSceneCard } from '@/components/features/device/CurrentSceneCard';
import { SceneCard } from '@/components/features/device/SceneCard';
import { router, useFocusEffect } from 'expo-router';
import { getDevices, createDevice, getDeviceDetails, deleteDevice, updateDeviceState, getDeviceStateHistory } from '../../api/device';
import { getScenes, createScene, getSceneDetails, updateScene, deleteScene, removeSceneDevice, adjustScenePriority, activateScene, getActiveScenes, switchScene } from '../../api/scene';
import getDeviceImage from '@/api/getDeviceImage';
import { getDisplayValueFromState } from '@/api/deviceStateMap';
import FontAwesome from '@expo/vector-icons/FontAwesome';

// 接口定义 (与你原来的一致)
interface DeviceData {
    id: number;
    name: string;
    type: string;
    family: string;
    meta?: Record<string, any>;
    state?: Record<string, any>;
}

interface SceneData {
    id: number;
    name: string;
    priority?: number;
    enabled?: boolean;
}

// 场景图片资源 (与你原来的一致)
const sceneImages = {
    1: require('../../assets/sceneImages/1.png'),
    2: require('../../assets/sceneImages/2.png'),
    3: require('../../assets/sceneImages/3.png'),
    4: require('../../assets/sceneImages/4.png'),
    5: require('../../assets/sceneImages/5.png'),
    6: require('../../assets/sceneImages/6.png'),
    7: require('../../assets/sceneImages/7.png'),
    8: require('../../assets/sceneImages/8.png'),
    9: require('../../assets/sceneImages/9.png'),
    default: require('../../assets/sceneImages/9.png'),
};

const getSceneImage = (scene: SceneData) => {
    const imageIndex = scene.id % 9 + 1;
    return sceneImages[imageIndex as keyof typeof sceneImages] || sceneImages.default;
};

export default function BlankScreen() {
    // --- State Management ---
    const [deviceList, setDeviceList] = useState<DeviceData[]>([]);
    const [sceneList, setSceneList] = useState<SceneData[]>([]);
    const [currentScene, setCurrentScene] = useState<SceneData | null>(null);
    const [sceneDevices, setSceneDevices] = useState<DeviceData[]>([]);
    const [isLoading, setIsLoading] = useState(true); // 统一的加载状态

    // --- Data Fetching Logic ---

    // 1. 将核心数据加载逻辑封装在 useCallback 中，以便复用
    const loadInitialData = useCallback(async () => {
        setIsLoading(true);
        try {
            // 并行获取场景和设备列表，提高效率
            const [scenesResponse, devicesResponse] = await Promise.all([
                getScenes(),
                getDevices()
            ]);

            const scenes = scenesResponse.data?.data?.scenes ?? [];
            const devices = devicesResponse.data?.data?.devices ?? [];

            setSceneList(Array.isArray(scenes) ? scenes : []);
            setDeviceList(Array.isArray(devices) ? devices : []);

            // 自动查找已启用的场景作为当前场景
            const enabledScene = scenes.find((s: SceneData) => s.enabled);
            setCurrentScene(enabledScene || scenes[0] || null);

        } catch (error) {
            console.error('Failed to load initial data:', error);
            Alert.alert('错误', '加载基础数据失败');
        } finally {
            setIsLoading(false);
        }
    }, []);

    // 2. 屏幕获得焦点时，执行核心数据加载
    useFocusEffect(
      useCallback(() => {
        loadInitialData();
      }, [loadInitialData])
    );

    // 3. 响应式地获取当前场景下的设备列表
    //    这个 effect 会在 currentScene 或 deviceList 更新后自动执行
    useEffect(() => {
        const fetchDevicesForCurrentScene = async () => {
            if (!currentScene) {
                setSceneDevices([]);
                return;
            }
            
            // 虽然 deviceList 已经获取，但仍需 getSceneDetails 来确认场景与设备的准确关联
            try {
                const response = await getSceneDetails(currentScene.id);
                if (response.data.ok && response.data.data) {
                    const sceneDetails = response.data.data;
                    const actionDeviceIds = sceneDetails.actions?.map((a: any) => a.device_id) || [];
                    
                    const devicesInScene = deviceList.filter(device =>
                        actionDeviceIds.includes(device.id)
                    );
                    setSceneDevices(devicesInScene);
                } else {
                    Alert.alert('错误', `无法加载场景 "${currentScene.name}" 的详情`);
                }
            } catch (error) {
                console.error(`Failed to fetch devices for scene ${currentScene.id}:`, error);
            }
        };

        fetchDevicesForCurrentScene();
    }, [currentScene, deviceList]); // 依赖清晰，数据流明确

    // --- User Action Handlers ---

    // 4. 优化的场景切换函数
    const handleSceneSelect = async (sceneToSelect: SceneData) => {
        if (sceneToSelect.id === currentScene?.id || isLoading) {
            return; // 如果点击的是当前场景或正在加载中，则不执行任何操作
        }

        setIsLoading(true);
        try {
            // 步骤 1: 调用 API 切换场景
            await switchScene(sceneToSelect.id);

            // 步骤 2: 乐观更新 UI，提供即时反馈
            setCurrentScene(sceneToSelect);
            setSceneList(prevList => 
                prevList.map(s => ({
                    ...s,
                    enabled: s.id === sceneToSelect.id,
                }))
            );

        } catch (error) {
            console.error('切换场景失败:', error);
            Alert.alert('错误', '切换场景失败');
            // 如果切换失败，重新从服务器同步一次状态，以纠正UI
            await loadInitialData();
        } finally {
            // 注意：这里的 setIsLoading(false) 将在 getSceneDetails 完成后触发
            // 为了更好的体验，可以把这个逻辑移动到上面的useEffect中
            setIsLoading(false);
        }
    };

    // 5. 创建新场景的函数
    const handleCreateScene = async () => {
        try {
            const response = await createScene({
                name: `新场景 ${sceneList.length + 1}`,
                description: '自动创建',
                enabled: false, // 建议默认创建为不激活状态，让用户手动配置和激活
            });
            Alert.alert('成功', '新场景已创建！');
            // 创建成功后，重新加载所有数据以显示新场景
            await loadInitialData();
        } catch (err) {
            Alert.alert('错误', '创建场景失败');
        }
    };

    // --- Render Logic ---

    // 初始加载时的占位符
    if (isLoading && !currentScene) {
        return (
            <View style={styles.centered}>
                <ActivityIndicator size="large" color="#888" />
            </View>
        );
    }

    return (
        <View style={styles.flexOne}>
            <ScrollView
                style={styles.scrollView}
                contentContainerStyle={styles.scrollViewContainer}
            >
                <View style={styles.centerAlign}>
                    {currentScene ? (
                        <CurrentSceneCard
                            image={getSceneImage(currentScene)}
                            title={currentScene.name}
                            desc={currentScene.enabled ? `已开启` : '已关闭'}
                            onEditPress={() => alert('编辑当前场景')}
                        />
                    ) : (
                        <CurrentSceneCard
                            image={require('../../assets/images/Scene.jpg')}
                            title="无可用场景"
                            desc="请点击下方加号创建一个新场景"
                            onEditPress={() => {}}
                        />
                    )}

                    <View style={styles.deviceGrid}>
                        {Array.from({ length: Math.ceil(sceneDevices.length / 2) }).map((_, rowIdx) => (
                            <View key={rowIdx} style={styles.deviceRow}>
                                {sceneDevices.slice(rowIdx * 2, rowIdx * 2 + 2).map(device => (
                                    <View key={device.id} style={styles.deviceCardWrapper}>
                                        <DeviceCard
                                            image={getDeviceImage(device.type)}
                                            title={device.name}
                                            desc={getDisplayValueFromState(device.state ?? {}) ?? '已停止'}
                                        />
                                    </View>
                                ))}
                            </View>
                        ))}
                    </View>
                </View>
            </ScrollView>

            {/* 底部场景选择器 */}
            <View style={styles.bottomBar}>
                <ScrollView
                    horizontal
                    showsHorizontalScrollIndicator={false}
                    contentContainerStyle={styles.sceneListContainer}
                >
                    {sceneList.map(scene => (
                        <View key={scene.id} style={styles.sceneCardWrapper}>
                            <SceneCard
                                image={getSceneImage(scene)}
                                title={scene.name}
                                onAddPress={() => handleSceneSelect(scene)}
                                enabled={scene.enabled}
                            />
                        </View>
                    ))}
                </ScrollView>
            </View>

            {/* 悬浮操作按钮 */}
            <TouchableOpacity style={styles.fabRight} onPress={handleCreateScene}>
                <FontAwesome name="plus-circle" size={50} color="#888" />
            </TouchableOpacity>

            <TouchableOpacity style={styles.bottomLeftButton} onPress={() => router.push('/SceneListPage')}>
                <Text style={styles.bottomLeftText}>进入场景列表</Text>
            </TouchableOpacity>

            {/* 全局加载遮罩 */}
            {isLoading && (
                <View style={styles.loadingOverlay}>
                    <ActivityIndicator size="large" color="#000" />
                </View>
            )}
        </View>
    );
}

// --- Styles ---
const styles = StyleSheet.create({
    centered: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#fff' },
    flexOne: { flex: 1 },
    scrollView: { flex: 1, backgroundColor: '#fff' },
    scrollViewContainer: { paddingBottom: 190 },
    centerAlign: { alignItems: 'center' },
    deviceGrid: { width: 330, marginTop: 16 },
    deviceRow: { flexDirection: 'row', justifyContent: 'space-between', marginBottom: 12 },
    deviceCardWrapper: { width: '48%', marginBottom: 8 },
    bottomBar: {
        position: 'absolute',
        left: 0,
        right: 0,
        bottom: 60,
        height: 120,
        backgroundColor: '#fff',
        borderTopWidth: 1,
        borderColor: '#eee',
        paddingVertical: 8,
    },
    sceneListContainer: { alignItems: 'center', paddingHorizontal: 16 },
    sceneCardWrapper: { marginRight: 16 },
    fabRight: {
        position: 'absolute',
        right: 40,
        bottom: 130, // 调整位置以避免与底部栏重叠
        width: 55,
        height: 55,
        borderRadius: 30,
        backgroundColor: '#fff',
        borderWidth: 1,
        borderColor: '#eee',
        justifyContent: 'center',
        alignItems: 'center',
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.2,
        shadowRadius: 3,
        elevation: 5,
    },
    bottomLeftButton: {
        position: 'absolute',
        left: 40,
        bottom: 180, // 调整位置以避免与底部栏重叠
        height: 55,
        justifyContent: 'center',
        alignItems: 'center',
    },
    bottomLeftText: { fontSize: 18, color: '#000', fontWeight: 'bold' },
    loadingOverlay: {
        ...StyleSheet.absoluteFillObject,
        backgroundColor: 'rgba(255, 255, 255, 0.7)',
        justifyContent: 'center',
        alignItems: 'center',
    },
});